package com.doraemon.controller.user;

import com.doraemon.constant.JwtClaimsConstant;
import com.doraemon.dto.UserLoginDTO;
import com.doraemon.entity.User;
import com.doraemon.properties.JwtProperties;
import com.doraemon.result.Result;
import com.doraemon.service.UserService;
import com.doraemon.utils.JwtUtil;
import com.doraemon.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * c端用户管理Controller
 **/
@RestController
@RequestMapping("/user/user")
@Slf4j
@Api(tags = "C端用户相关接口")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties; // 注入JWT配置属性

    /***
     * 微信用户登陆
     * ---
     * @param userLoginDTO 用户登陆DTO类(前端参数)
     * @return: com.doraemon.result.Result<com.doraemon.vo.UserLoginVO>
     */
    @PostMapping("/login")
    @ApiOperation("微信登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("c端-微信用户登陆：{}", userLoginDTO.getCode());

        // 调用Service层 wxLogin 方法，获取查询到的用户实体
        User user = userService.wxLogin(userLoginDTO);

        // 登陆成功后，为微信用户生成JWT令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        // 构建用户登陆VO类
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build(); // 通过@Builder注解构建

        return Result.success(userLoginVO);
    }

}
